package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userSerlvet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 封装User对象
        User user = new User(username, password);

        // 调业务层的登录方法
        UserServiceImpl service = new UserServiceImpl();
        List<User> list = service.login(user);

        // 判断是否查询出了结果
        if (list.size() !=0){
            // 将用户名存入会话域中
            req.getSession().setAttribute("username",username);
            // 响应给客户端
            resp.getWriter().write("true");
        }else {
            resp.getWriter().write("false");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
